/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Server;

import Model.Book;




import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import javax.swing.JOptionPane;

/**
 *
 * @author Admin //file server phu la chi co ham ko co bat cu phuong thuc chay
 * hay thread nao
 *
 */
public class ServerBook {

    ObjectInputStream inObject;
    ObjectOutputStream outObject;

    public ServerBook(ObjectInputStream inObject, ObjectOutputStream outObject) {
        this.inObject = inObject;
        this.outObject = outObject;

    }

    public void showBook() {
        //  Book book = new Book();
        ArrayList<Book> arrayBook = new ArrayList();
        arrayBook = ShowAllBook(1);

        try {
            outObject.writeObject(arrayBook);

        } catch (IOException ex) {
            System.out.println(ex);
        }

    }

    public void showBookBorrow() {//Hien sach cho table borrow
        //  Book book = new Book();
        ArrayList<Book> arrayBook = new ArrayList();
        arrayBook = ShowAllBook(0);
        try {
            outObject.writeObject(arrayBook);
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

    public void deleteBook() {
        try {
            Book book = (Book) inObject.readObject();//nhan doi tuong login do client goi         
            outObject.writeObject(DeleteBook(book));      //goi thong bao cho client                
        } catch (IOException | ClassNotFoundException ex) {
            System.out.println(ex); //in loi
        }


    }

    public void editBook() {
        try {
            Book book = (Book) inObject.readObject();//nhan doi tuong login do client goi         
            outObject.writeObject(EditBook(book));      //goi thong bao cho client                
        } catch (IOException | ClassNotFoundException ex) {
            System.out.println(ex);
        }
    }

    public void searchBookID() {
        try {
            String keyword = (String) inObject.readObject(); //nhan keyword-tu tim kiem tu client
            int j = (int) inObject.readObject();
            Book book = new Book();
            book = SearchBookID(keyword, j);
            outObject.writeObject(book);
        } catch (IOException | ClassNotFoundException ex) {
            System.out.println(ex);
        }

    }

    public void searchTitleOrCategory() {
        try {
            String strIN = (String) inObject.readObject(); //nhan keyword-tu tim kiem,index của cbo,j tu client
            String[] arrIN = strIN.split("#");
            String keyword = arrIN[0];
            int index = Integer.parseInt(arrIN[1]);
            int j = Integer.parseInt(arrIN[2]);
            Book book = new Book();
            ArrayList<Book> arrBook = new ArrayList();
            arrBook = SearchTitleOrCategory(keyword, index - 1, j);
            outObject.writeObject(arrBook);

        } catch (IOException | ClassNotFoundException | NumberFormatException ex) {
            System.out.println(ex);
        }
    }

    public void searchAuthor() {
        try {
            String strIN = (String) inObject.readObject(); //nhan keyword-tu tim kiem,index của cbo,j tu client
            String[] arrIN = strIN.split("#");
            String keyword = arrIN[0];
            int j = Integer.parseInt(arrIN[1]);
            Book book = new Book();
            ArrayList<Book> arrBook = new ArrayList();
            arrBook = SearchAuthor(keyword, j);
            outObject.writeObject(arrBook);

        } catch (IOException | ClassNotFoundException | NumberFormatException ex) {
            System.out.println(ex);
        }
    }

    public void insertBook() {
        try {
            Book book = (Book) inObject.readObject();// nhan book tu client
            outObject.writeObject(AddBook(book));      //goi thong bao cho client
        } catch (IOException | ClassNotFoundException ex) {
            System.out.println(ex);
        }
    }

//   public void insertCategory() {
//            try {
//              
//             Category cate= = (Category)inObject.readObject();// nhan book tu client
//            outObject.writeObject(book.AddBook());      //goi thong bao cho client
//        } catch (IOException | ClassNotFoundException ex) {
//            System.out.println(ex);
//        }  
//    }
//  public String BookReturnCategoryName(String CategoryID) {
//        Category cate = new Category();
//        return cate.returnCategoryName(CategoryID);
//    }
    private boolean checkBookID(String bookID) {
        Connection con = (Connection) MyConnect.getConnect();
        try {
            String sql = "select * from Book where BookID='" + bookID + "'";
            Statement stm = con.createStatement();
            ResultSet rs = stm.executeQuery(sql);
            if (rs.next()) {
                //   JOptionPane.showMessageDialog(null, "Duplicate key BookID");
                return true;
            }
        } catch (Exception e) {
            //   JOptionPane.showMessageDialog(null, "checkBookID: " + e.getMessage());
            System.out.println(e);
            return true;
        }

        return false;
    }

    public boolean AddBook(Book book) {
        if (checkBookID(book.BookID)) {
            return false;
        }
        try {
            Connection cn = (Connection) MyConnect.getConnect();
            PreparedStatement pst = cn.prepareStatement("insert Book values(?,?,?,?,?,?,?)");
            pst.setString(1, book.BookID);
            pst.setString(2, book.Title);
            pst.setString(3, book.Author);
            pst.setString(4, book.Sumary);
            pst.setString(5, book.CategoryID);
            pst.setString(6, book.Publisher);
            pst.setBoolean(7, true);
            //Chay lenh Insert
            pst.executeUpdate();
            pst.close();
            cn.close();
            return true;
        } catch (Exception e) {
            System.out.println(e);
            //  JOptionPane.showMessageDialog(null, "AddBook\n" + e.getMessage());
            return false;
        }
    }

    public boolean EditBook(Book book) {
        try {
            Connection cn = (Connection) MyConnect.getConnect();
            String sql = "update Book set Title=?,Author=?,Sumary=?,CategoryID=?,Publisher=? where BookID=? ";
            PreparedStatement pst = cn.prepareStatement(sql);
            pst.setString(1, book.Title);
            pst.setString(2, book.Author);
            pst.setString(3, book.Sumary);
            pst.setString(4, book.CategoryID);
            pst.setString(5, book.Publisher);
            pst.setString(6, book.BookID);
            pst.executeUpdate();
            pst.close();
            cn.close();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Edit Book\n" + ex.getMessage());
            return false;
        }
        return true;
    }

    public boolean DeleteBook(Book book) {
        try {
            Connection cn = MyConnect.getConnect();
            String sql = "delete from Book where BookID=?";
            PreparedStatement pst = cn.prepareStatement(sql);
            pst.setString(1, book.BookID);
            pst.executeUpdate();
            pst.close();
            cn.close();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Delete Book" + ex.getMessage());
            return false;
        }
        return true;
    }

    public ArrayList<Book> Search(String keyWord, int i, int j) {
        return null;

    }

//    @Override
//    public String toString() {
//        return String.format("%s %s %s %s \n%s \n%s %s", BookID, Title, Author, Sumary, CategoryID, Publisher, Active ? "True" : "False");
//    }
    public ArrayList<Book> ShowAllBook(int i) {
        //i la co hien sach active=false khong
        //1 la hien, 0 la khong hien
        ServerCategory cate = new ServerCategory();
        Connection con = MyConnect.getConnect();
        ArrayList<Book> arrBook = new ArrayList<Book>();
        try {
            Statement stm = con.createStatement();
            String sql = "select * from Book";
            ResultSet rs = stm.executeQuery(sql);
            while (rs.next()) {
                Book b = new Book();
                b.BookID = rs.getString(1);
                b.Title = rs.getString(2);
                b.Author = rs.getString(3);
                b.Sumary = rs.getString(4);
                b.CategoryID = rs.getString(5);
                b.Publisher = rs.getString(6);
                b.Active = rs.getBoolean(7);
                b.setCategoryName(cate.returnCategoryName(b.CategoryID));
                if (i == 1) {
                    arrBook.add(b);
                } else {
                    if (b.Active) {
                        arrBook.add(b);
                    }
                }
            }
            return arrBook;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /*    
     *          Chuc nang Search 
     * 
     */
    public ArrayList<Book> SearchTitleOrCategory(String keyWord, int i, int j) {
        //i la so thu tu de tim theo Title hay la Category
        //i =1 title, i =2 category
        ServerCategory cate = new ServerCategory();
        Connection cn = MyConnect.getConnect();
        ArrayList<Book> tb = new ArrayList<>();

        //j la co` de co  chon them  cac sach co active bang false vao khong
        //0 neu them vao, 1 neu khong them vao
        try {
            Statement stm = cn.createStatement();
            ResultSet rs = null;
            if (i == 1) {
                String sqlTitle = "select * from Book where Title='" + keyWord + "'";
                rs = stm.executeQuery(sqlTitle);
            } else if (i == 2) {

                String sqlCategory = "select * from Book where CategoryID='" + cate.returnCategoryID(keyWord) + "'";
                rs = stm.executeQuery(sqlCategory);
            }

            while (rs.next()) {
                Book b = new Book();
                b.BookID = rs.getString(1);
                b.Title = rs.getString(2);
                b.Author = rs.getString(3);
                b.Sumary = rs.getString(4);
                b.CategoryID = rs.getString(5);
                b.Publisher = rs.getString(6);
                b.Active = rs.getBoolean(7);
                b.setCategoryName(cate.returnCategoryName(b.CategoryID));
                if (j == 1) {
                    if (b.Active == true) {
                        tb.add(b);
                    }
                } else {
                    tb.add(b);
                }

            }
            return tb;
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Search by Title or Category: " + ex.getMessage());
            return null;
        }
    }

    public Book SearchBookID(String keyWord, int j) {
        Connection cn = MyConnect.getConnect();                     //j la co` de co them cac sach co active bang false vao khong
        //0 neu them vao, 1 neu khong them vao
        ServerCategory cate = new ServerCategory();
        String sqlBookID = "select * from Book where BookID ='" + keyWord + "'";
        try {
            Statement stm = cn.createStatement();
            Book b = new Book();
            ResultSet rs = null;
            rs = stm.executeQuery(sqlBookID);
            rs.next();
            b.BookID = rs.getString(1);
            b.Title = rs.getString(2);
            b.Author = rs.getString(3);
            b.Sumary = rs.getString(4);
            b.CategoryID = rs.getString(5);
            b.Publisher = rs.getString(6);
            b.Active = rs.getBoolean(7);
            b.setCategoryName(cate.returnCategoryName(b.CategoryID));
            if (j == 1) {
                if (b.Active == true) {
                    return b;
                } else {                    
                    return null;
                }
            } else {
                return b;
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Search by BookID: " + ex.getMessage());
            return null;
        }
    }

    public ArrayList<Book> SearchAuthor(String keyWord, int j) {
        ServerCategory cate = new ServerCategory();
        Connection cn = MyConnect.getConnect();
        ArrayList<Book> tb = new ArrayList<>();
        //j la co` de co  chon them  cac sach co active bang false vao khong
        //0 neu them vao, 1 neu khong them vao
        try {
            Statement stm = cn.createStatement();
            ResultSet rs = null;
            String sqlAuthor = "select * from Book where Author='" + keyWord + "'";
            rs = stm.executeQuery(sqlAuthor);



            while (rs.next()) {
                Book b = new Book();
                b.BookID = rs.getString(1);
                b.Title = rs.getString(2);
                b.Author = rs.getString(3);
                b.Sumary = rs.getString(4);
                b.CategoryID = rs.getString(5);
                b.Publisher = rs.getString(6);
                b.Active = rs.getBoolean(7);
                b.setCategoryName(cate.returnCategoryName(b.CategoryID));
                if (j == 1) {
                    if (b.Active == true) {
                        tb.add(b);
                    }
                } else {
                    tb.add(b);
                }

            }
            return tb;
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Search by Author: " + ex.getMessage());
            return null;
        }
    }
}
